package com.xxgc.mq.config;


import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    // 交换机名称
    private final String EXCHANGE_NAME = "study_exchange";

    // 队列名称
    private final String QUEUE_NAME = "study_queue";

    /**
     * 创建交换机(手机)
     * */
    @Bean("myExchange")
    public Exchange getExchange(){
        return ExchangeBuilder
                .topicExchange(EXCHANGE_NAME)
                .durable(true) // 是否持久化
                .build();
    }

    /**
     * 创建队列(讨论的事情)
     * 后续具体功能把my换成对应的功能名
     * */
    @Bean("myQueue")
    public Queue getMessageQueue(){
        return QueueBuilder
                .durable(QUEUE_NAME)
                .ttl(10000) // 消息在队列里的存活时间 单位：ms
                .build();
    }

    /**
     * 交换机和队列的绑定（手机和事情）
     * */
    @Bean
    public Binding bindingExchangeQueue(
            @Qualifier("myExchange") Exchange exchange, // @Qualifier
            @Qualifier("myQueue") Queue queue){
        return BindingBuilder
                .bind(queue)
                .to(exchange)
                .with("#.spz.#")// 审判长梗
                .noargs();
    }

    /**
     *
     * @return
     */
    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory){
        RabbitTemplate rabbitTemplate = new RabbitTemplate();
        rabbitTemplate.setConnectionFactory(connectionFactory);
        //开启强制回调
        rabbitTemplate.setMandatory(true);
        //发送信息到MQ的回调
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean b, String s) {
                if (b){
                    System.out.println("消息已成功推送到MQ");
                }else{
                    System.out.println("相关配置信息"+correlationData);
                    System.out.printf("原因"+s);
                }
            }
        });
        return rabbitTemplate;
    }
}
